package com.mm.mweather

import android.annotation.SuppressLint
import android.content.Intent
import android.content.SharedPreferences
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.preference.PreferenceManager
import android.support.annotation.Nullable
import android.support.v4.view.GravityCompat
import android.support.v4.widget.DrawerLayout
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.app.AppCompatActivity
import android.view.LayoutInflater
import android.view.TextureView
import android.view.View
import android.widget.*
import com.bumptech.glide.Glide
import com.mm.mweather.gson.Aqi
import com.mm.mweather.gson.Forecast
import com.mm.mweather.gson.Suggestion
import com.mm.mweather.gson.Weather
import com.mm.mweather.util.HttpUtil
import com.mm.mweather.util.Utility
import kotlinx.android.synthetic.main.aqi.*
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import java.io.IOException

class WeatherActivity: AppCompatActivity() {
    private var weatherlayout: ScrollView? = null
    private var titleCity: TextView? = null
    private var titleUpdateTime: TextView? = null
    private var degreeText: TextView? = null
    private var weatherInfoText: TextView? = null
    private var forecastLayout: LinearLayout? = null
    private var apiText: TextView? = null
    private var pm25Text: TextView? = null
    private var comfortText: TextView? = null
    private var carWashText: TextView? = null
    private var sportText: TextView? = null
    private var bingPicImg: ImageView? = null

    private var swipeRefresh:SwipeRefreshLayout?=null

    private var mWeatherId:String? = null



    private var navButton:Button?=null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_weather)
        //初始化控件
        weatherlayout = findViewById<View>(R.id.weather_layout) as ScrollView
        titleCity = findViewById<View>(R.id.title_city) as TextView
        titleUpdateTime = findViewById<View>(R.id.title_time) as TextView
        degreeText = findViewById<View>(R.id.degree_text) as TextView
        weatherInfoText = findViewById<View>(R.id.weather_info_text) as TextView
        forecastLayout = findViewById<LinearLayout>(R.id.forecast_layout)
        apiText = findViewById<View>(R.id.aqi_text) as TextView
        pm25Text = findViewById<View>(R.id.pm25_text) as TextView
        comfortText = findViewById<View>(R.id.comfort_text) as TextView
        carWashText = findViewById<View>(R.id.car_wash_text) as TextView
        sportText = findViewById<View>(R.id.sport_text) as TextView
        bingPicImg = findViewById<View>(R.id.bing_pic_img) as ImageView


        if (Build.VERSION.SDK_INT > 21) {
            var decorView: View = window.decorView
            decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE

            window.statusBarColor = Color.TRANSPARENT
        }

        swipeRefresh = findViewById<SwipeRefreshLayout>(R.id.swipe_refresh)

        swipeRefresh!!.setColorSchemeResources(R.color.colorPrimary)

        swipeRefresh!!.setOnRefreshListener {


            resquestWeather(mWeatherId!!)
        }


        var prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(this@WeatherActivity)

        mWeatherId = getIntent().getStringExtra("weather_id")
        weatherlayout!!.visibility = View.VISIBLE
        resquestWeather(mWeatherId!!)
        resquestapi(mWeatherId!!)

        var bingPic: String? = prefs.getString("bing_pic", null)
        if (bingPic !== null) {

            Glide.with(this@WeatherActivity).load(bingPic).into(bingPicImg)
        } else {
            loadBingPic()
        }


        navButton = findViewById<Button>(R.id.nav_button)

        navButton!!.setOnClickListener { v ->


        }

    }
    fun resquestWeather(weatherId:String){
        mWeatherId=weatherId
        var address:String="https://free-api.heweather.net/s6/weather?location="+weatherId+"&key=f9aeb541625441499a2b8d89aba9e08c"
        HttpUtil.sendOkHttpRequests(address, object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                runOnUiThread {
                    Toast.makeText(this@WeatherActivity, "获取天气信息失败", Toast.LENGTH_SHORT).show()
                    swipeRefresh!!.isRefreshing = false
                }
            }


            override fun onResponse(call: Call, response: Response) {
                val resposeText = response.body()!!.string()
                val weather:Weather=Utility.handleWeatherResponse(resposeText)
                runOnUiThread {
                    if (weather!=null&&"ok".equals(weather.status)){
                        var editor:SharedPreferences.Editor=PreferenceManager.getDefaultSharedPreferences(this@WeatherActivity).edit()
                        editor.putString("weather",resposeText)
                        editor.apply()
                        showWeatherInfo(weather)
                    }
                    swipeRefresh!!.isRefreshing = false
                }
            }
        })
    }


    fun resquestapi(weatherId:String){
        mWeatherId=weatherId
        var address:String="https://free-api.heweather.net/s6/air/now?location="+weatherId+"&key=f9aeb541625441499a2b8d89aba9e08c"
        HttpUtil.sendOkHttpRequests(address, object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                runOnUiThread {
                    Toast.makeText(this@WeatherActivity, "获取空气质量信息失败", Toast.LENGTH_SHORT).show()
                    swipeRefresh!!.isRefreshing = false
                }
            }


            override fun onResponse(call: Call, response: Response) {
                val resposeText = response.body()!!.string()
                val aqi:Aqi=Utility.handleAqiResponse(resposeText)
                runOnUiThread {
                    if (aqi!=null){

                        showAqiInfo(aqi)
                    }
                    swipeRefresh!!.isRefreshing = false
                }
            }
        })
    }

    fun showWeatherInfo( weather: Weather){
        var cityName:String?= weather.basic!!.cityName
        var updateTime:String?=weather.update!!.loc
        var degree:String? = weather.now!!.tempterature + "℃"
        var weatherInfo:String? = weather.now!!.info

        titleCity!!.text = cityName
        titleUpdateTime!!.text = updateTime
        degreeText!!.text = degree
        weatherInfoText!!.text = weatherInfo

        forecastLayout!!.removeAllViews()

        for (forecast in weather.forecastList!!){
            var view:View=LayoutInflater.from(this).inflate(R.layout.forecast_item,forecastLayout,false)
            var dateText:TextView = view.findViewById<View>(R.id.date_text) as TextView
            var infoText:TextView = view.findViewById<View>(R.id.info_text) as TextView
            var maxText:TextView = view.findViewById<View>(R.id.max_text) as TextView
            var minText:TextView = view.findViewById<TextView>(R.id.min_text)

            dateText.text=forecast.date
            infoText.text=forecast.info
            maxText.text=forecast.tempterature_max
            minText.text=forecast.tempterature_min
            forecastLayout!!.addView(view)


        }
        var comfSuggestion:Suggestion = weather.suggestionList!!.findLast { o->o.type=="comf" }!!

        comfortText!!.text="舒适度："+comfSuggestion.brf+","+comfSuggestion.txt

        var cwSuggestion:Suggestion = weather.suggestionList!!.findLast { o->o.type=="cw" }!!
        carWashText!!.text="洗车指数："+cwSuggestion.brf+","+cwSuggestion.txt

        var sportuggestion:Suggestion = weather.suggestionList!!.findLast { o->o.type=="sport" }!!
        sportText!!.text="运动建议："+sportuggestion.brf+","+sportuggestion.txt



    }
    fun showAqiInfo(aqi:Aqi){

        var aqis:String?=aqi.aqiInfo!!.aqi
        var pm25:String?= aqi.aqiInfo!!.pm25

        aqi_text.text=aqis
        pm25_text.text=pm25

        weatherlayout!!.visibility=View.VISIBLE
    }

    fun loadBingPic(){
        val picUrl:String = "http://guolin.tech/api/bing_pic";
        HttpUtil.sendOkHttpRequests(picUrl,object : Callback{

            override fun onFailure(call: Call?, e: IOException?) {
                e!!.printStackTrace()
            }


            override fun onResponse(call: Call?, response: Response) {
               val bingPic:String=response.body()!!.string()

               var editor:SharedPreferences.Editor=PreferenceManager.getDefaultSharedPreferences(this@WeatherActivity).edit()
                editor.putString("bing_pic",bingPic)
                editor.apply()
                runOnUiThread{
                    Glide.with(this@WeatherActivity).load(bingPic).into(bingPicImg)

                }
            }
        })
    }
}
